package com.android.lovely.ui.adapter

import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.core.view.updateLayoutParams
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.android.lovely.data.CardItem
import com.android.lovely.databinding.ItemDetailCardBinding
import com.android.lovely.ext.loadBlurredImage
import com.android.lovely.ext.loadWithPlaceholder
import com.kotlin.extensions.dimen.Dimension.dp
import com.kotlin.extensions.inflater.LayoutInflaterExt.layoutInflater
import com.kotlin.extensions.view.ViewExt.clickable

class DetailRobotCardsAdapter : ListAdapter<CardItem, DetailRobotCardsAdapter.CardViewHolder>(object :
    DiffUtil.ItemCallback<CardItem>() {
    override fun areItemsTheSame(oldItem: CardItem, newItem: CardItem): Boolean {
        return oldItem.id == newItem.id
    }

    override fun areContentsTheSame(oldItem: CardItem, newItem: CardItem): Boolean {
        return oldItem == newItem
    }

}) {
    var onItemClickListener: ((CardItem, Int) -> Unit)? = null

    class CardViewHolder(
        parent: ViewGroup, val binding: ItemDetailCardBinding = ItemDetailCardBinding.inflate(
            parent.layoutInflater, parent, false
        )
    ) : RecyclerView.ViewHolder(binding.root)

    override fun onBindViewHolder(holder: CardViewHolder, position: Int) {
        val item = getItem(position) ?: return
        holder.binding.apply {
            clLock.isVisible = item.isUnlock.not()
            if (item.isUnlock) {
                ivImage.loadWithPlaceholder(item.cardUrl)
            } else {
                ivImage.loadBlurredImage(item.cardUrl)
            }
            ivOpen.isVisible = item.isUnlock
            tvCollect.text = item.intimacyValue.toString()
            tvDiamond.text = item.point.toString()
            tvCollect.isVisible = item.intimacyValue > 0
            tvDiamond.isVisible = item.point > 0
            tvOr.isVisible = item.intimacyValue > 0 && item.point > 0
            root.clickable { onItemClickListener?.invoke(item, position) }
            val current = position % 2
            if (current == 0) {
                root.updateLayoutParams<ViewGroup.MarginLayoutParams> {
                    marginStart = 10.dp
                    marginEnd = 5.dp
                }
            } else {
                root.updateLayoutParams<ViewGroup.MarginLayoutParams> {
                    marginStart = 5.dp
                    marginEnd = 10.dp
                }
            }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CardViewHolder {
        return CardViewHolder(parent)
    }

    override fun getItemViewType(position: Int): Int {
        return 983948234
    }
}